import React from 'react';
import { Table, Button, Popconfirm } from 'antd';
import { connect } from 'dva';
import EditableCell from '../components/EditableTable';
import styles from './UsersManage.css';

class Rolesmanage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      dataSource: [],
    };
  }
  componentDidMount() {
    this.props.dispatch({
      type: 'role/getRoles',
      payload: {
        page_no: 1,
        page_size: 5,
      },
    });
  }

  componentWillReceiveProps(nextProps) {
    this.setState({
      dataSource: nextProps.role.roleList.data,
    });
  }
  onCellChange = (key) => {
    return (value) => {
      this.props.dispatch({
        type: 'role/editRole',
        payload: {
          id: key._id,
          role_name: value,
        },
      });
    };
  }
  onDelete = (key) => {
    this.props.dispatch({
      type: 'role/deleteRole',
      payload: {
        id: key._id,
      },
    });
  }
  handleAdd = () => {
    const newData = {
      role_name: '管理员',
      mids: [],
      apis: [],
      memo: '这是个管理员',
      status: 1,
    };
    this.props.dispatch({
      type: 'role/addRole',
      payload: {
        ...newData,
      },
    });
  }
  render() {
    const columns = [{
      key: '_id',
      title: 'ID',
      dataIndex: '_id',
    }, {
      title: '权限名称',
      dataIndex: 'role_name',
      width: '40%',
      render: (text, record) => (
        <EditableCell
          value={text}
          onChange={this.onCellChange(record)}
        />
      ),
    }, {
      title: '操作',
      dataIndex: 'operation',
      render: (text, record) => {
        return (
          this.state.dataSource.length >= 1 ?
            (
              <div>
                <Popconfirm title="确定删除此权限？" onConfirm={() => this.onDelete(record)}>
                  <a href="" style={{ paddingLeft: 10 }}>删除权限</a>
                </Popconfirm>
              </div>
            ) : null
        );
      },
    }];
    return (
      <div>
        <Button className={styles.toorbar} onClick={this.handleAdd}>新增权限</Button>
        <Table
          bordered
          dataSource={this.state.dataSource}
          columns={columns}
          pagination={{
          defaultPageSize: 5,
          pageSize: 5,
          showTotal: () => {
              return `共 ${this.state.dataSource.length} 条数据`;
          },
        }}
        />
      </div>
    );
  }
}


export default connect(({ role }) => ({
  role,
}))(Rolesmanage);

